package com.nuanshui.heatedloan.web;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.nuanshui.heatedloan.entity.cms.security.Module;
import com.nuanshui.heatedloan.entity.cms.security.User;
import com.nuanshui.heatedloan.entity.cms.security.UserRole;
import com.nuanshui.heatedloan.extension.shiro.ShiroDbRealm;
import com.nuanshui.heatedloan.service.cms.security.AdminUserService;
import com.nuanshui.heatedloan.service.cms.security.FrontUserService;
import com.nuanshui.heatedloan.service.cms.security.ModuleService;
import com.nuanshui.heatedloan.service.cms.security.UserRoleService;
import com.nuanshui.heatedloan.util.SecurityConstants;
import com.nuanshui.heatedloan.util.UserUtil;
import com.nuanshui.heatedloan.util.dwz.AjaxObject;

/**
 * Index控制器
 */
@Controller
@RequestMapping("/cms/manage")
public class CmsIndexController extends ApiController{

	@Autowired
	private AdminUserService userService;

	@Autowired
	private UserRoleService userRoleService;

	@Autowired
	private ModuleService moduleService;
	
	@Autowired
	private FrontUserService frontUserService;
	
	@Autowired
	private ShiroDbRealm shiroRealm;
	
	@Autowired
	private PasswordEncoder pwdEncoder;

	/**
	 * 进入首页
	 * 
	 * @param request
	 * @return
	 */
	@RequiresAuthentication
	@RequestMapping(value = "index", method = RequestMethod.GET)
	public String index(final HttpServletRequest request) {

		return redirectIndexUrl(request,"index");

	}

	/**
	 * 进入测试首页
	 *
	 * @param request
	 * @return
	 */
	@RequiresAuthentication
	@RequestMapping(value = "testIndex", method = RequestMethod.GET)
	public String testIndex(final HttpServletRequest request) {

		return redirectIndexUrl(request,"testIndex");

		//return "cms/index/index";
	}

	private String redirectIndexUrl(final HttpServletRequest request,String redirectUrl) {

		// User user = userService.get(shiroUser.getLoginName());
		// 1、设置用户角色
		final List<UserRole> userRoles = userRoleService.find(UserUtil
				.getCurrentUserId());
		UserUtil.getCurrentUser().setUserRoles(userRoles);

		final Module menuModule = getMenuModule(userRoles);

		// 2、在session中放入user
		request.getSession().setAttribute(SecurityConstants.LOGIN_USER,
				UserUtil.getCurrentUser());
		// 放入用户有权限查看的模块
		request.setAttribute("menuModule", menuModule);
		// 放置系统公告
		return redirectUrl;

		//return "cms/index/index";
	}

	/**
	 * 返回用户有权限查看的模块
	 * 
	 * @param userRoles
	 * @return 返回用户有权限查看的模块的根节点
	 */
	private Module getMenuModule(final List<UserRole> userRoles) {
		// 1、得到当前用户的所有权限
		final Set<String> permissionSet = Sets.newHashSet();
		for (final UserRole userRole : userRoles) {
			final Set<String> tmp = Sets.newHashSet(userRole.getRole()
					.getPermissionList());
			permissionSet.addAll(tmp);
		}
		// 2、组装菜单,只获取二级菜单，再多的话就需要递归了
		final Module rootModule = moduleService.getTree();// 拿到所有的模块
		final List<Module> list1 = Lists.newArrayList();// 用于装一级菜单
		for (final Module m1 : rootModule.getChildren()) {
			// 只加入拥有view权限的Module
			// 假如这个大模块有view的权限，再看看里面的小模块有没有view权限
			if (permissionSet.contains(m1.getSn() + ":"
					+ SecurityConstants.OPERATION_VIEW)) {
				final List<Module> list2 = Lists.newArrayList();// 用于装二级菜单
				for (final Module m2 : m1.getChildren()) {// 遍历下面的二级菜单
					if (permissionSet.contains(m2.getSn() + ":"
							+ SecurityConstants.OPERATION_VIEW)) {
						list2.add(m2);
					}
				}
				m1.setChildren(list2);// 把二级菜单放在一级菜单中
				list1.add(m1);// 将符合条件的一级菜单放好
			}
		}
		rootModule.setChildren(list1);// list1中都是符合条件的一级菜单

		return rootModule;
	}

	/**
	 * 修改密码
	 */
	@SuppressWarnings("unused")
	@RequestMapping(value = "/user/index/updatePwd",method = RequestMethod.POST)
	@ResponseBody
	public String updatePassword(final HttpServletRequest request,final String oldPassword, final String plainPassword,final String rPassword) {
		final User user = (User) request.getSession().getAttribute(SecurityConstants.LOGIN_USER);
		//判断当前用户是不是app端用户
		Integer frontUserId = userService.loadFrontUserIdByAdminUserId(user.getId());
		boolean flag=frontUserService.checkPassWord(frontUserId.toString(), oldPassword);
		//判断原密码输入是否正确
		if(!flag){
			return fail("密码修改失败,原密码不正确");
		}
		//新旧密码不能相同
		if(oldPassword.equals(plainPassword)){
			return fail("密码修改失败,新旧密码相同");
		}
		// 两次输入的密码一样
		if (plainPassword.equals(rPassword)) {
			user.setPlainPassword(plainPassword);
			if(frontUserId == null){
				userService.update(user);
			}else{
				frontUserService.updatePassWord(frontUserId, plainPassword);
			}
			return success("密码修改成功");
		}
		return fail("密码修改失败！");
	}

	/**
	 * 跳转到修改用户信息的界面
	 */
	@RequestMapping(value = "/updateBase", method = RequestMethod.GET)
	public String preUpdate() {
		return "cms/index/updateBase";
	}

	/**
	 * 修改用户信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/user/index/updateBase", method = RequestMethod.POST)
	@ResponseBody
	public String update(final User user, final HttpServletRequest request,
			final MultipartFile photos,final String nick) {
		final User loginUser = (User) request.getSession().getAttribute(
				SecurityConstants.LOGIN_USER);
        if(StringUtils.isNotEmpty(nick)){
        	Integer frontUserId = userService.loadFrontUserIdByAdminUserId(loginUser.getId());
        	if(frontUserId !=null){
        	   //修改users表中用户昵称
        	   frontUserService.updateNick(frontUserId, nick);
        	}
        	  //修改cms_security_user表中用户昵称
        	userService.updateUserNick(loginUser.getId().toString(),nick);
        	return success("修改成功");
        }
        return fail("修改失败！");
	}
}
